// import vue from '../../main';
import { showDialog } from 'vant';
import { HTTP, localUrl, baseUrl, grayUrl } from './authUserHttp';
import { type result, type userInfo } from '../..//types/userInfo';
import getUrlParamValue from '../../util/getUrlParamValue';

function _getH5UserInfo(jsonParam: object) {
  console.log(jsonParam);
  let requestUrl = baseUrl + '/interfaces/oathor/getH5UserInfo.do';
  return HTTP.post(requestUrl, jsonParam);
}

function _localUserInfo(): userInfo {
  const info = sessionStorage.getItem('personInfo') || false;
  if (!info) {
    throw new Error('no UserInfo');
  }
  return JSON.parse(info);
}

function getUserInfo(): Promise<userInfo> {
  return new Promise(async (resolve, reject) => {
    let userInfo = sessionStorage.getItem('personInfo') || '';
    // console.log(userInfo);

    if (userInfo) {
      resolve(_localUserInfo());
      return;
    }
    let accessToken = getUrlParamValue('accessToken');
    let code = getUrlParamValue('code');
    if (!accessToken && !code) {
      return;
    }
    if (accessToken) {
      let browser = navigator.userAgent.toLowerCase();
      if (browser.match(/Alipay/i)) {
        sessionStorage.setItem('type', 'al');
      } else {
        sessionStorage.setItem('type', 'wx');
      }
    } else {
      sessionStorage.setItem('type', 'app');
    }
    let param = {
      accessToken,
      code,
    };
    let result: result;
    result = await _getH5UserInfo({
      jsonParam: JSON.stringify(param),
    }) as result;
    try {
      if (result.success) {
        let data = {
          ...result.data,
          name: result.data.zwdtsw_name,
          idcard: result.data.zwdtsw_cert_id,
          mobile: result.data.zwdtsw_link_phone,
          token: result.tokenSno,
          userId: result.data.zwdtsw_user_id,
        };
        sessionStorage.setItem('personInfo', JSON.stringify(data));
        sessionStorage.setItem('tokenSNO', result.tokenSno);
        resolve(data);
      } else {
        showDialog({
          title: '温馨提示',
          message: '网络波动，请重新尝试～',
          confirmButtonText: '好的',
          confirmButtonColor: '#CBB486',
        })
        console.error(result);
      }
    } catch (error) {
      showDialog({
        title: '温馨提示',
        message: '网络波动，请重新尝试～',
        confirmButtonText: '好的',
        confirmButtonColor: '#CBB486',
      })
      console.error(error);
    }
  });
}

export { getUserInfo, _localUserInfo };
